/*package com.utils.spring;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.kyhd.mogen.controller.model.DeleteRequest;
import com.kyhd.mogen.controller.model.MogenRequest;
import com.kyhd.mogen.controller.model.MogenResponse;
import com.kyhd.mogen.controller.model.MogenResponse.MogenItem;
import com.kyhd.mogen.controller.model.ReqContext;
import com.kyhd.mogen.service.BaseInfoService;
import com.kyhd.mogen.service.CustomerInvoiceService;
import com.kyhd.mogen.service.ExcelService;
import com.kyhd.mogen.service.MediaInfoService;
import com.kyhd.mogen.service.MediaInvoiceService;
import com.kyhd.mogen.service.MogenService;
import com.kyhd.mogen.util.Constant;
import com.kyhd.mogen.util.DateUtil;
import com.kyhd.mogen.util.ReqCtxUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;



@Api("财务管理接口")
@RestController
@Slf4j
@RequestMapping(value = "/mogen/api/", produces = {"application/json" })
public class MogenController {
	@Autowired
	BaseInfoService baseInfoService;
	@Autowired
	CustomerInvoiceService customerInvoiceService;
	@Autowired
	MediaInvoiceService mediaInvoiceService;
	@Autowired
	MediaInfoService mediaInfoService;
	@Autowired
	MogenService mogenService;
	@Autowired
	ExcelService excelService; 
	// 文件上传路径
	@Value("${file.upload.path}")
	String filePath;
	
	@ApiOperation(value="查询(下拉框选项传数字)", notes="")
	@RequestMapping(method={RequestMethod.POST},path="/search")
	public @ResponseBody MogenResponse search(@RequestBody MogenRequest request) {
		log.info("mogen search request:{}",request);
		MogenResponse response = new MogenResponse();
		if(StringUtil.isBlank(request.getSettlementEDate())||StringUtil.isBlank(request.getSettlementSDate())) {
			response.setState(Constant.API_STATUS_FAILED);
			response.setMsg("请选择结算期间");
			return response;
		}
		if(request.getLimit()<=0) 
			request.setLimit(100);
		if(request.getOffset()<=0) 
			request.setOffset(1);
		try {
			response = this.mogenService.search(request);
			response.setState(Constant.API_STATUS_SUCCESS);
			response.setMsg("success");
		} catch (Exception e) {
			e.printStackTrace();
			response.setState(Constant.API_STATUS_FAILED);
			response.setMsg("系统异常，请稍后再试");
		}
		log.info("mogen search response:{}",response);
		return response;
	}
	
	@ApiOperation(value="根据ID查询(下拉框选项传数字)", notes="")
	@RequestMapping(method={RequestMethod.GET},path="/query")
	public @ResponseBody MogenResponse queryById(
			@ApiParam(value="ID")@RequestParam(name="id",required=true) long id) {
		log.info("mogen QueryById request id:{}",id);
		MogenResponse response = new MogenResponse();
		if(id<=0){
			response.setState(Constant.API_STATUS_FAILED);
			response.setMsg("违法的ID");
			return response;
		}
		try {
			response = this.mogenService.QueryById(id);
			response.setState(Constant.API_STATUS_SUCCESS);
			response.setMsg("success");
		} catch (Exception e) {
			e.printStackTrace();
			response.setState(Constant.API_STATUS_FAILED);
			response.setMsg("系统异常，请稍后再试");
		}
//		log.info("mogen search response:{}",response);
		return response;
	}
	
	@ApiOperation(value="编辑(下拉框选项传字符串)", notes="")
	@RequestMapping(method={RequestMethod.POST},path="/edit")
	public @ResponseBody ResponseEntity<String> edit(@RequestBody MogenItem request) {
		log.info("mogen edit request:{}",request);
		HttpHeaders headers = new HttpHeaders();
		headers.put(HttpHeaders.CONTENT_TYPE, Arrays.asList("application/json;charset=UTF-8"));
		JSONObject ret = new JSONObject();
		ReqContext reqContext = ReqCtxUtil.reqContext.get();
		int operateType = reqContext.getOperateType();
		String operator = reqContext.getName();
		
		if(operateType<Constant.OperateType.普通.getType()&&operateType>=Constant.OperateType.超管.getType()) {
			if(request.getId()<=0) {
				ret.put("state", Constant.API_STATUS_FAILED);
				ret.put("msg", "编辑失败，不存在的ID");	
			}else {
				ret = this.mogenService.edit(request, operator);
				if(ret.getIntValue("state")==Constant.API_STATUS_FAILED) {
					log.info("mogen edit response:{}",ret.toJSONString());
					return new ResponseEntity<String>(ret.toJSONString(), headers, HttpStatus.OK);
				}
				ret.put("state", Constant.API_STATUS_SUCCESS);
				ret.put("msg", "编辑成功");	
			}
		}else {
			ret.put("state", Constant.API_STATUS_FAILED);
			ret.put("msg", "无法编辑，权限不足");	
		}
		
		log.info("mogen edit response:{}",ret.toJSONString());
		return new ResponseEntity<String>(ret.toJSONString(), headers, HttpStatus.OK);
	}
	
	@ApiOperation(value="删除", notes="")
	@RequestMapping(method={RequestMethod.POST},path="/delete")
	public @ResponseBody ResponseEntity<String> delete(@RequestBody DeleteRequest request
			//@ApiParam(value = "IDS")@RequestParam(name = "ids",required = true) List<Long> ids
			) {
		log.info("mogen delete resquest:{}",request.getIds());
		HttpHeaders headers = new HttpHeaders();
		headers.put(HttpHeaders.CONTENT_TYPE, Arrays.asList("application/json;charset=UTF-8"));
		JSONObject ret = new JSONObject();
		ReqContext reqContext = ReqCtxUtil.reqContext.get();
		int operateType = reqContext.getOperateType();
		String operator = reqContext.getName();

		try {
			if(operateType<Constant.OperateType.普通.getType()&&operateType>=Constant.OperateType.超管.getType()) {
//				for (Long id : request.getIds()) {
//					this.mogenService.deleteById(id,operator);
//				}
				this.mogenService.deleteByIds(request.getIds(),operator);
			}else {
				ret.put("state", Constant.API_STATUS_FAILED);
				ret.put("msg", "删除失败，权限不足");	
			}
			ret.put("state", Constant.API_STATUS_SUCCESS);
			ret.put("msg", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			ret.put("state", Constant.API_STATUS_FAILED);
			ret.put("msg", "删除失败，系统异常");
		}
		log.info("mogen delete response:{}",ret.toJSONString());
		return new ResponseEntity<String>(ret.toJSONString(), headers, HttpStatus.OK);
	}  

	@ApiOperation(value="导入", notes="")
	@RequestMapping(method={RequestMethod.POST},path="/import")
	public @ResponseBody ResponseEntity<String> importExcel(
			@ApiParam(value = "待上传的文件") @RequestParam(name = "file") MultipartFile file) {
		HttpHeaders headers = new HttpHeaders();
		headers.put(HttpHeaders.CONTENT_TYPE, Arrays.asList("application/json;charset=UTF-8"));
		JSONObject ret = new JSONObject();
		ReqContext reqContext = ReqCtxUtil.reqContext.get();
		int operateType = reqContext.getOperateType();
		String operator = reqContext.getName();
		if(operateType>=Constant.OperateType.普通.getType()) {
			ret.put("state", Constant.API_STATUS_FAILED);
			ret.put("msg", "无法导入，权限不足");	
			return new ResponseEntity<String>(ret.toJSONString(), headers, HttpStatus.OK);
		}
		
		boolean isUpdate = false;
		if(operateType==Constant.OperateType.超管.getType()) {
			isUpdate = true;
		}
		
		String fileName = "";
		try {
			// 上传文件到服务器
			fileName = file.getOriginalFilename();
			String suffixName = fileName.substring(fileName.lastIndexOf("."));
			log.info("上传的文件名为：" + fileName + " ， 上传的后缀名为：" + suffixName);
			// 解决中文问题，liunx下中文路径，图片显示问题
			fileName = UUID.randomUUID() + suffixName;
			byte[] bytes = file.getBytes();
			BufferedOutputStream buffStream = new BufferedOutputStream(
					new FileOutputStream(new File(filePath, fileName)));
			buffStream.write(bytes);
			buffStream.close();
		} catch (Exception e) {
			e.printStackTrace();
			String errorMsg1 = "文件导入异常,原因:" + e.getMessage();
			ret.put("status", Constant.API_STATUS_FAILED);
			ret.put("msg", errorMsg1);
			log.info("mogen import response:{}", ret.toJSONString());
		}

		// 读取excel文件内容
		List<MogenItem> mogenItemReadList = new ArrayList<>();
		String errorMsg = this.excelService.batchImport(filePath, fileName, mogenItemReadList);
		if (StringUtils.isNotEmpty(errorMsg)) {
			ret.put("status", Constant.API_STATUS_FAILED);
			ret.put("msg", errorMsg);
			return new ResponseEntity<String>(ret.toJSONString(), headers, HttpStatus.OK);
		}

		// 处理内容结果集
		int successNum = 0;
		int failedNum = 0;
//		Map<String, String> importMsg = Maps.newHashMap();
		List<JSONObject> importMsgList = Lists.newArrayList();
		try {
			for (MogenItem mi : mogenItemReadList) {
				if (StringUtil.isBlank(mi.getSettlementDate()) || StringUtil.isBlank(mi.getSettlementMode())
						|| StringUtil.isBlank(mi.getProduct()) || StringUtil.isBlank(mi.getBelongBackstage())
						|| StringUtil.isBlank(mi.getReceiveRefundAttribute())
						|| StringUtil.isBlank(mi.getCustomerPaymentName())) {
					JSONObject importMsg = new JSONObject();
					importMsg.put("name", String.format(Constant.EXCELLINE, mi.getExcelLine()+""));
					importMsg.put("info", Constant.ImportMsg.getMsg(1));
					importMsgList.add(importMsg);
					failedNum++;
					continue;
				}else if((!DateUtil.isYMDB(mi.getSettlementDate()))&&(!DateUtil.isYMDBS(mi.getSettlementDate()))) {
					JSONObject importMsg = new JSONObject();
					importMsg.put("name", String.format(Constant.EXCELLINE, mi.getExcelLine()+""));
					importMsg.put("info", Constant.ImportMsg.getMsg(2)+":"+mi.getSettlementDate());
					importMsgList.add(importMsg);
					failedNum++;
					continue;
				}else if(Constant.SettlementMode.getType(mi.getSettlementMode().toUpperCase().replace(Constant.SETTLEMENT_MODE_SYMBOL, ""))<=0) {
					JSONObject importMsg = new JSONObject();
					importMsg.put("name", String.format(Constant.EXCELLINE, mi.getExcelLine()+""));
					importMsg.put("info", Constant.ImportMsg.getMsg(3)+":"+mi.getSettlementMode());
					importMsgList.add(importMsg);
					failedNum++;
					continue;
				}else if(Constant.ReceiveRefundAttribute.getType(mi.getReceiveRefundAttribute())<=0) {
					JSONObject importMsg = new JSONObject();
					importMsg.put("name", String.format(Constant.EXCELLINE, mi.getExcelLine()+""));
					importMsg.put("info", Constant.ImportMsg.getMsg(4)+":"+mi.getReceiveRefundAttribute());
					importMsgList.add(importMsg);
					failedNum++;
					continue;
				}else if(StringUtil.isNotBlank(mi.getCustomerRebateAttribute())&&
						Constant.CustomerRebateAttribute.getType(mi.getCustomerRebateAttribute())<=0) {
					JSONObject importMsg = new JSONObject();
					importMsg.put("name", String.format(Constant.EXCELLINE, mi.getExcelLine()+""));
					importMsg.put("info", Constant.ImportMsg.getMsg(5)+":"+mi.getCustomerRebateAttribute());
					importMsgList.add(importMsg);
					failedNum++;
					continue;
				}else if(StringUtil.isNotBlank(mi.getCustomerInvoiceType())&&
						Constant.CustomerInvoiceType.getType(mi.getCustomerInvoiceType())<=0) {
					JSONObject importMsg = new JSONObject();
					importMsg.put("name", String.format(Constant.EXCELLINE, mi.getExcelLine()+""));
					importMsg.put("info", Constant.ImportMsg.getMsg(6)+":"+mi.getCustomerInvoiceType());
					importMsgList.add(importMsg);
					failedNum++;
					continue;
				}else if(StringUtil.isNotBlank(mi.getMediaRebateAttribute())&&
						Constant.MediaRebateAttribute.getType(mi.getMediaRebateAttribute())<=0) {
					JSONObject importMsg = new JSONObject();
					importMsg.put("name", String.format(Constant.EXCELLINE, mi.getExcelLine()+""));
					importMsg.put("info", Constant.ImportMsg.getMsg(7)+":"+mi.getMediaRebateAttribute());
					importMsgList.add(importMsg);
					failedNum++;
					continue;
				}else if(StringUtil.isNotBlank(mi.getMediaInvoiceType())&&
						Constant.MediaInvoiceType.getType(mi.getMediaInvoiceType())<=0) {
					JSONObject importMsg = new JSONObject();
					importMsg.put("name", String.format(Constant.EXCELLINE, mi.getExcelLine()+""));
					importMsg.put("info", Constant.ImportMsg.getMsg(8)+":"+mi.getMediaInvoiceType());
					importMsgList.add(importMsg);
					failedNum++;
					continue;
				}else if(StringUtil.isNotBlank(mi.getAccessPrice())&&mi.getAccessPrice().indexOf(".")>-1
						&&mi.getAccessPrice().substring(mi.getAccessPrice().indexOf(".")+1, mi.getAccessPrice().length()).length()>2) {
					JSONObject importMsg = new JSONObject();
					importMsg.put("name", String.format(Constant.EXCELLINE, mi.getExcelLine()+""));
					importMsg.put("info", Constant.ImportMsg.getMsg(9)+":"+mi.getAccessPrice());
					importMsgList.add(importMsg);
					failedNum++;
					continue;
				}else if(mi.getId()<=0&&this.mogenService.exist(mi)) {
					JSONObject importMsg = new JSONObject();
					importMsg.put("name", String.format(Constant.EXCELLINE, mi.getExcelLine()+""));
					importMsg.put("info", Constant.ImportMsg.getMsg(10));
					importMsgList.add(importMsg);
					failedNum++;
					continue;
				}
				
				boolean isSave = false;
				try {
					isSave = this.mogenService.save(mi,operator,operateType,isUpdate);
					if(isSave) {
						successNum++;
					}else {
						JSONObject importMsg = new JSONObject();
						importMsg.put("name", String.format(Constant.EXCELLINE, mi.getExcelLine()+""));
						importMsg.put("info", Constant.ImportMsg.getMsg(11));
						importMsgList.add(importMsg);
						failedNum++;
						continue;
					}
				} catch (Exception e) {
					e.printStackTrace();
					if(!isSave) {
						JSONObject importMsg = new JSONObject();
						importMsg.put("name", String.format(Constant.EXCELLINE, mi.getExcelLine()+""));
						importMsg.put("info", Constant.ImportMsg.getMsg(11)+","+e.getMessage());
						importMsgList.add(importMsg);
						failedNum++;
						continue;
					}
				}
		
			}
		} catch (Exception e) {
			e.printStackTrace();
			String errorMsg1 = "文件读取异常,原因:" + e.getMessage();
			ret.put("status", Constant.API_STATUS_FAILED);
			ret.put("msg", errorMsg1);
			log.info("mogen import response:{}", ret.toJSONString());
		}

		ret.put("status", Constant.API_STATUS_SUCCESS);
		ret.put("successNum", successNum);
		ret.put("failedNum", failedNum);
		ret.put("msg", importMsgList);
//		log.info("mogen import response:{}", ret.toJSONString());
		return new ResponseEntity<String>(ret.toJSONString(), headers, HttpStatus.OK);
	}
	
}
*/